package com.atguigu.tingshu.account.receiver;

import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.model.user.UserInfo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;


@Service
@Component
public class AccountReceiver {
    @Autowired
    private UserAccountService userAccountService;

    /**
     * 接收消息并创建用户账户
     * 该方法监听RabbitMQ队列，当接收到消息时，根据用户ID创建一个新的用户账户，
     * 并初始化账户的总金额和可用金额最后确认消息处理
     *
     * @param userId 用户ID，用于创建用户账户
     * @param message 接收到的消息对象，包含消息的属性和内容
     * @param channel 消息通道，用于确认消息处理
     */
    @RabbitListener(bindings = @QueueBinding(
            value =@Queue(value = MqConst.QUEUE_USER_REGISTER,durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_USER,durable = "true"),
            key = MqConst.ROUTING_USER_REGISTER
    ))
    public void receive(Long userId, Message message, Channel channel) {
        // 创建用户账户实例
        UserAccount userAccount = new UserAccount();
        // 设置用户账户的用户ID
        userAccount.setUserId(userId);
        // 初始化用户账户的总金额为1000
        userAccount.setTotalAmount(new BigDecimal(1000));
        // 初始化用户账户的可用金额为1000
        userAccount.setAvailableAmount(new BigDecimal(1000));
        // 保存用户账户信息
        userAccountService.save(userAccount);
        // 确认消息处理
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
